/**
 * 
 */
package model.container.vertices;

import java.util.HashMap;
import java.util.LinkedList;

import model.Edge;

/**
 *
 */
public class AdjacencyList extends Vertices {
	public static class Node {
		int value;
		int cost;

		/**
		 * @return the Edge corresponding
		 */
		public int getValue() {
			return value;
		}

		/**
		 * @return The distance to the root
		 */
		public int getCost() {
			return cost;
		}

		public Node(int v, int c) {
			value = v;
			cost = c;
		}

		@Override
		public String toString() {
			return "to="+value+":cost="+cost;
		}
	}

	private HashMap<Integer, LinkedList<Node>> items = new HashMap<Integer, LinkedList<Node>>();

	public AdjacencyList() {
	}

	@Override
	public String toString() {
		return items.toString();
	}

	/**
	 * Add an empty starting Node to the Container
	 * @param from the starting Node
	 */
	private void addRoot(int from) {
		if(items.get(from) == null) {
			items.put(from, new LinkedList<Node>());
			//System.out.println(this.getClass()+" [+] New root node "+from);
		}
	}

	@Override
	public void addItem(int from, int to, int co) {
		addRoot(from);
		addRoot(to);
		items.get(from).add(new Node(to, co));
		//System.out.println(this.getClass()+" [+] Adding "+to+" after "+from+" ("+co+")");
	}

	/**
	 * Get the neighbors of the <b>from</b> Node
	 * @param from the Node the neighbors are getting from
	 * @return a LinkedList of <b>from</b>'s neighbors 
	 */
	public LinkedList<Node> getItemList(int from) {
		return items.get(from);
	}

	/**
	 * Get the neighbors of the <b>from</b> Node
	 * @param e the <b>from</b> Node's Edge 
	 * @return a LinkedList of <b>from</b>'s neighbors
	 * @see AdjacencyList#getItem(int) 
	 */
	public LinkedList<Node> getItemList(Edge e) {
		return getItemList(e.getFrom());
	}
	
	/**
	 * Get the distance between two Nodes if registered in the List 
	 * @param from starting Node
	 * @param from ending Node
	 * @return the distance between the Nodes, -1 if the Edge is not registered
	 */
	public int getDistance(int from, int to) {
		LinkedList<Node> l = getItemList(from);
		if(l == null)
			return -1;
		for(Node n : l)
			if(n.getValue() == to)
				return n.getCost();
		return -1;
	}
	
	/**
	 * Get a random Item (acually the first)
	 */

	/**
	 * @see AdjacencyList#getDistance(int, int)
	 */
	public int getDistance(Edge e) {
		return getDistance(e.getFrom(), e.getTo());
	}

	@Override
	public boolean isEmpty() {
		return items.isEmpty();
	}
	
	@Override
	public int getSize() {
		return items.size();
	}
}
